<template>
    <div class="h-full flex flex-col">
        <el-scrollbar wrap-class="flex-1" view-class="p-5">
            <el-form
                :model="attendanceMachine"
                ref="formRef"
                size="large"
                label-width="100px"
            >
                <el-form-item
                    v-for="(machine, index) in attendanceMachine"
                    :key="machine.key"
                    :label="`#${index + 1} 设备：`"
                >
                    <el-row :gutter="20" class="flex-1">
                        <el-col :span="4">
                            <el-form-item
                                :prop="index + '.name'"
                                :rules="nameRules"
                            >
                                <el-input
                                    v-model="machine.name"
                                    placeholder="请输入设备名称"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item
                                :prop="index + '.ip'"
                                :rules="ipRules"
                            >
                                <el-input
                                    v-model="machine.ip"
                                    placeholder="请输入设备的ip"
                                />
                            </el-form-item>
                        </el-col>
                        <el-button
                            type="danger"
                            :icon="Delete"
                            @click.prevent="removeMachine(machine)"
                        />
                    </el-row>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addMachine"
                        >新增设备</el-button
                    >
                    <el-button type="primary" @click="PasswordSetting"
                        >密码设置</el-button
                    >
                    <el-button type="primary" @click="handleApply"
                        >保存</el-button
                    >
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </div>
    <PasswordDialog ref="setNameDialog" :visible="state.visible" />
</template>
<script setup>
import {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElScrollbar,
    ElMessage,
    ElSpace,
    ElSwitch,
    ElDialog
} from 'element-plus'
import { validateUrl } from '@/utils/validate-fn'
import { requestedMessage } from '@/utils/asynchronous'
import { Delete, Check, Back } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, inject } from 'vue'
import PasswordDialog from '@/components/dialog/PasswordDialog.vue'

/**
 * 弹框
 */
const setNameDialog = ref()
/**
 * 密码弹框
 */
const state = reactive({
    visible: false
})

const inited = inject('inited')

const formRef = ref()

const attendanceMachine = ref([{ key: 1, name: '', ip: null, DST: false }])

const nameRules = {
    validator: (rule, value, cb) => {
        if (!value) {
            cb('请输入设备名称')
        } else if (
            attendanceMachine.value.filter((item) => item.name === value)
                .length > 1
        ) {
            cb('该设备名称产生冲突 请检查')
        } else {
            cb()
        }
    },
    trigger: 'blur'
}

const ipRules = {
    validator: (rule, value, cb) => {
        if (!value) {
            cb('请输入设备ip')
        } else if (!validateUrl(value)) {
            cb('ip格式错误 请检查')
        } else if (
            attendanceMachine.value.filter((item) => item.ip === value).length >
            1
        ) {
            cb('该设备ip产生冲突 请检查')
        } else {
            cb()
        }
    },
    trigger: 'blur'
}

onMounted(() => {
    const machine = localStorage.getItem('machine')
    console.log('---------' + machine)
    if (machine) {
        console.log('++++++++++' + machine)
        attendanceMachine.value = JSON.parse(machine)
        inject('inited').value = true
    } else {
        let xhr = new XMLHttpRequest()
        xhr.open('GET', 'equipment.txt', false) // public文件夹下的绝对路径
        xhr.overrideMimeType('text/html;charset=utf-8')
        xhr.send(null)
        const LocalFile = xhr.responseText
        if (LocalFile) {
            console.log('本地文件' + LocalFile)
            attendanceMachine.value = JSON.parse(LocalFile)
            inject('inited').value = true
            localStorage.setItem(
                'machine',
                JSON.stringify(attendanceMachine.value)
            )
        }
    }
})

/**
 * 删除
 */
function removeMachine(item) {
    const index = attendanceMachine.value.indexOf(item)
    if (index > 0) {
        attendanceMachine.value.splice(index, 1)
    } else {
        ElMessage({
            showClose: true,
            message: '最少保留一台设备',
            type: 'error',
            grouping: true
        })
    }
}

/**
 * 新增设备
 */
function addMachine() {
    attendanceMachine.value.push({
        key: Date.now(),
        ip: null,
        DST: false
    })
}

/**
 * 保存
 */
function handleApply() {
    submitForm(formRef.value)
}
/**
 * 保存
 */
function submitForm(formEl) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            localStorage.setItem(
                'machine',
                JSON.stringify(attendanceMachine.value)
            )
            ElMessage({
                showClose: true,
                message: '设置成功',
                type: 'success',
                grouping: true
            })
            inited.value = true
        } else {
            ElMessage({
                showClose: true,
                message: '请完成所有设备的ip设置',
                type: 'warning',
                grouping: true
            })
            inited.value = false
            return false
        }
    })
}

/**
 * 密码设置
 */
function PasswordSetting() {
    setNameDialog.value.open()
}

/**
 * 文件
 */
function saveFile() {
    let xhr = new XMLHttpRequest()
    let okStatus = document.location.protocol === 'file:' ? 0 : 200
    xhr.open('GET', 'equipment.txt', false) // public文件夹下的绝对路径
    xhr.overrideMimeType('text/html;charset=utf-8')
    xhr.send(null)
    xhr.console.log(xhr.responseText) // xhr.responseText为文本中的内容
}
</script>

<style></style>
